import React from 'react'
import PropTypes from 'prop-types'
import moment from 'moment'
import { Upload, Button, message, Modal, Popconfirm, Progress, Spin } from 'antd'
import styles from './index.less'

export default class extends React.PureComponent {

  static propTypes = {
    filetype: PropTypes.array,
    uploadFile: PropTypes.func
  }

  static defaultProps = {
    filetype: ['jpg', 'gif', 'png', 'jpeg', 'bmp', 'psd', 'doc', 'docx', 'xls', 'xlsx', 'rar', 'zip', 'ppt', 'pptx', 'mp4', 'txt',
      'rp', 'pdf', 'wps', 'dps', 'et', 'xmind', 'mp3', 'ogg'
    ],
    uploadFile: () => {}
  }

  state = {
    name: 'file',
    action: '/project/Upload/uploadFile',
    headers: {},
    multiple: true,

    percent: 0,
    speed: 0,
    loaded: 0,
    fileSize: 0
  }

  componentDidMount() {
    const token = window.localStorage.getItem('token') || ''
    this.setState({ headers: { Authorization: `Bearer ${token}` } })
  }

  beforeUpload = file => {
    const { filetype } = this.props

    const filename = file.name
    const suffix = filename.substr(filename.lastIndexOf('.') + 1)
    const flag = filetype.includes(suffix)

    this.setState(state => ({
      ...state,
      // 上传之前保存文件大小
      fileSize: file.size,
      // 上传之前显示弹框
      visible: true
    }))

    if (!flag) {
      message.error('文件格式不被允许!')
    }
    const isLt100M = file.size / 1024 / 1024 < 100
    if (!isLt100M) {
      this.handleHiddenModel()
      message.error('文件大小超过 100MB!')
    }
    return flag && isLt100M
  }

  onProgress = (step) => {
    const { timeStamp } = step
    const milliseconds = moment.duration(timeStamp).milliseconds()
    this.setState(state => ({
      ...state,
      percent: step.percent,
      speed: (step.loaded - state.loaded) / 1048576 / (milliseconds / 1000),
    }), () => {
      this.setState(state => ({
        ...state,
        loaded: step.loaded,
      }))
    })
  }

  uploadFile = info => {
    const { uploadFile } = this.props
    uploadFile(info)

    if (info.file.status === 'done') {
      this.handleHiddenModel()
    } else if (info.file.status === 'error') {
      this.handleHiddenModel()
    }

  }

  handleHiddenModel = () => {
    this.setState(state => ({
      ...state,
      // 上传完成之后关闭弹窗
      visible: false
    }))
  }

  render() {

    const { children } = this.props
    const { visible, percent, speed, loaded, fileSize } = this.state

    return (
      <React.Fragment>
        <Upload {...this.state} showUploadList={false} onChange={this.uploadFile} beforeUpload={this.beforeUpload} onProgress={this.onProgress}>
          {children}
        </Upload>
        <Modal
          width={400}
          visible={visible}
          maskClosable={false}
          closable={false}
          footer={null}
          bodyStyle={{padding: 16}}
          destroyOnClose='true'
        >
          <Spin size="small" />
          <Progress percent={percent} strokeWidth={5} status="active" showInfo={false} />
          <section className={styles.progress}>
            <span>{speed.toFixed(2)}M/s</span>
            <span> {(loaded / 1048576).toFixed(2)} M / {(fileSize / 1048576).toFixed(2)} M </span>
          </section>
          <section style={{textAlign: 'center'}}>
            <Popconfirm title="终止上传文件?" onConfirm={() => message.warning('功能开发中')} okText="是" cancelText="否">
              <Button type="danger" icon="minus-circle-o" size="small">终止上传</Button>
            </Popconfirm>
          </section>
        </Modal>
      </React.Fragment>
    )
  }
}